package cn.tedu.luban.passport.main.controller;

import cn.tedu.luban.passport.protocol.common.enums.PassportResultEnum;
import com.google.code.kaptcha.Producer;
import com.tedu.inn.protocol.exception.BusinessException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

@Api(
    value = "验证码",
    tags = "验证码"
)
@RestController
@Slf4j
public class VCodeController {
    private static final String SESSION_VCODE="vcode";
    @Autowired
    private Producer producer;
    //TODO 限流逻辑，不允许频繁访问验证码接口
    @GetMapping("sso/valid/code")
    @ApiOperation("获取验证码")
    public void getVCode(
        @ApiIgnore HttpServletRequest request,
        @ApiIgnore HttpServletResponse response,
        @ApiIgnore HttpSession session) throws BusinessException {
        String text = producer.createText();
        session.setAttribute(SESSION_VCODE,text);
        log.info("当前验证码:{}",text);
        BufferedImage image = producer.createImage(text);
        response.setHeader("Access-Control-Expose-Headers", "VALID-CODE");
        //将图片输出给浏览器
        response.setContentType("image/png");
        try {
            OutputStream os = response.getOutputStream();
            ImageIO.write(image, "png", os);
        } catch (IOException e) {
            throw new BusinessException(PassportResultEnum.CREATE_VCODE_FAILED);
        }
    }
}
